//
//  NSString+MarsSafeUrlCode.m
//  WKWebDemo
//
//  Created by yangpenghua on 2018/3/27.
//  Copyright © 2018年 linzi. All rights reserved.
//

#import "NSString+MarsSafeUrlCode.h"

@implementation NSString (MarsSafeUrlCode)

/**
 *  @brief  mars_urlEncode
 *
 *  @return mars_urlEncode 后的字符串
 */
- (NSString *)mars_urlEncode {
    return [self mars_urlEncodeUsingEncoding:NSUTF8StringEncoding];
}
/**
 *  @brief  mars_urlEncode
 *
 *  @param encoding encoding模式
 *
 *  @return mars_urlEncode 后的字符串
 */
- (NSString *)mars_urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,
                                                              (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,                                                 kCFStringEncodingUTF8));
    
    return encodedString;
}
/**
 *  @brief  mars_urlDecode
 *
 *  @return mars_urlDecode 后的字符串
 */
- (NSString *)mars_urlDecode {
    return [self mars_urlDecodeUsingEncoding:NSUTF8StringEncoding];
}
/**
 *  @brief  mars_urlDecode
 *
 *  @param encoding encoding模式
 *
 *  @return mars_urlDecode 后的字符串
 */
- (NSString *)mars_urlDecodeUsingEncoding:(NSStringEncoding)encoding {
    return (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                 (__bridge CFStringRef)self,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(encoding));
}
/**
 *  @brief  url query转成NSDictionary
 *
 *  @return NSDictionary
 */
- (NSDictionary *)mars_dictionaryFromURLParameters
{
    NSArray *pairs = [self componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val = [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [params setObject:val forKey:[kv objectAtIndex:0]];
    }
    return params;
}

@end
